/*
 * MySnsGatewayManager.cpp
 *
 *  Created on: May 16, 2011
 *      Author: MongKieu
 */

#include "../inc/Model/TwitterMySnsGatewayManager.h"
#include "../inc/Ui/TwitterLoginForm.h"
#include "../inc/Ui/TwitterForm.h"
#include "../inc/Ui/TwitterMyProfileForm.h"
#include "../inc/Ui/TwitterMyFollowingForm.h"

using namespace Osp::Base;
using namespace Osp::Social;
using namespace Osp::Social::Services;
using namespace Osp::App;
using namespace Osp::Base::Collection;
using namespace Osp::Ui::Controls;
MySnsGatewayManager::MySnsGatewayManager() :
	__pSnsGateway(null), __pBuddyMemberList(null), __isMyProfile(false),
			__pPagingParam(null), __pPagingParamBuddies(null) {
	// TODO Auto-generated constructor stub

}

MySnsGatewayManager::~MySnsGatewayManager() {
	// TODO Auto-generated destructor stub
	if (__pSnsGateway != null){
		delete __pSnsGateway;
	}
}
bool MySnsGatewayManager::Initialize() {
	result r = E_SUCCESS;

	//create SnsGateway instance
	__pSnsGateway = new SnsGateway();
	r = __pSnsGateway->Construct(*this, null, this, this);
	if (IsFailed(r)) {
		AppLog("__pSnsGateway->Construct() is failed by %s.", GetErrorMessage(r));
		return false;
	}

	__pBuddyMemberList = new ArrayList();
	return true;
}
void MySnsGatewayManager::AddTwitterAuthResult(
		const Osp::Social::Services::SnsAuthResult& authResult) {
	result r = E_SUCCESS;
	//Frame* pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
	//TwitterManager* pMgr = static_cast<TwitterManager*> (pFrame->GetControl(L"TwitterMgr"));

	if (authResult.GetTokenKey().IsEmpty()) {
		AppLog("Fail to AddTwitterAuthResult. No token key.");
		return;
	}

	r = __pSnsGateway->AddAuthResult(authResult);
	if (IsFailed(r)) {
		AppLog("Fail to AddAuthResult. [%s]", GetErrorMessage(r));
	}
}
//pMgr->ClearActivityList();}
void MySnsGatewayManager::RemoveTwitterAuthResult(void) {
	result r = E_SUCCESS;

	r = __pSnsGateway->RemoveAuthResult(L"twitter");
	if (IsFailed(r))
	{
		AppLog("Fail to RemoveAuthResult. [%s]", GetErrorMessage(r));
	}
}
void MySnsGatewayManager::RequestActivities(void) {
	SnsPagingParam pagingParam(10);
	String activityOwner = L"all";
	RequestId reqId;
	result r = E_SUCCESS;

	r = __pSnsGateway->GetStatusText(L"twitter", null, reqId);
	if (IsFailed(r))
	{
		AppLog("Fail to GetStatusText. [%s]", GetErrorMessage(r));
	}

	r = __pSnsGateway->GetActivities(L"twitter", &activityOwner, pagingParam,reqId);
		if (IsFailed(r))
		{
			AppLog("Fail to GetActivities. [%s]", GetErrorMessage(r));
		}
}
bool MySnsGatewayManager::RequestMoreActivities(void) {
	String activityOwner = L"all";
	RequestId reqId;
	result r = E_SUCCESS;

	if (__pPagingParam == null)
	{
		return false;
	}

	r = __pPagingParam->Next();
	if (IsFailed(r))
	{
		AppLog("No more page.");
		__pPagingParam->Reset();
	}

	r = __pSnsGateway->GetActivities(L"twitter", &activityOwner, *__pPagingParam, reqId);
	if(r==E_SUCCESS)
	{
		AppLog("Sucess");
	}
	if(r==E_INVALID_STATE )
	{
		AppLog("invalid state");
	}
	if(r==E_INVALID_ARG)
	{
		AppLog("invalid arg");
	}
	if (IsFailed(r))
	{
		AppLog("Fail to GetActivities. [%s]", GetErrorMessage(r));
		return false;
	}

	return true;
}
bool MySnsGatewayManager::RequestHomeActivies() {
	String activityOwner = "all";
	RequestId reqId;
	result r = E_SUCCESS;
	if (__pPagingParam == null) {
		__pPagingParam = new SnsPagingParam(10);

		AppLog("Paging=null");
		return false;
	}
	__pPagingParam->Reset();
	r = __pSnsGateway->GetActivities(L"twitter", &activityOwner, *__pPagingParam, reqId);
	if (IsFailed(r))
	{
		AppLog("Fail to GetActivities. [%s]", GetErrorMessage(r));
		return false;
	}
	return true;
}
bool MySnsGatewayManager::RequesrMoreFriends() {

	RequestId reqId;
	result r = E_SUCCESS;
	if (__pPagingParamBuddies == null) {
		return false;
	}
	r = __pPagingParamBuddies->Next();
	if (IsFailed(r)) {

		return false;
	}
	r = __pSnsGateway->GetMyBuddies(L"twitter", *__pPagingParamBuddies, reqId);
	if(IsFailed(r))
	{
		AppLog("Fail to GetMyBuddies. [%s]", GetErrorMessage(r));
	}
	return true;
}
bool MySnsGatewayManager::RequestHomeFriends() {
	RequestId reqId;
	result r = E_SUCCESS;
	if (__pPagingParamBuddies == null) {
		__pPagingParamBuddies = new SnsPagingParam(10);
		AppLog("Paging=null");
		return false;
	}
	__pPagingParamBuddies->Reset();
	r = __pSnsGateway->GetMyBuddies(L"twitter", *__pPagingParamBuddies, reqId);
	if(IsFailed(r))
	{
		AppLog("Fail to GetMyBuddies. [%s]", GetErrorMessage(r));
	}
	return true;
}
bool MySnsGatewayManager::CheckLoginStatus(void) {
	result r = E_SUCCESS;
	RequestId reqId;

	r = __pSnsGateway->IsLoggedIn(L"twitter", reqId);
	if (IsFailed(r))
	{
		return false;
	}
	return true;
}
void MySnsGatewayManager::RequestMyProfile() {
	RequestId reqId;
	result r = E_SUCCESS;
	__isMyProfile = true;
	r = __pSnsGateway->GetProfile(L"twitter", null, reqId);
	if(IsFailed(r))
	{
		AppLog("Fail to GetProfile. [%s]", GetErrorMessage(r));
	}

}
void MySnsGatewayManager::RequestMyUserNameFromProfile() {
	RequestId reqId;
	result r = E_SUCCESS;
	__isGetMyUserNameProfile = true;
	r = __pSnsGateway->GetProfile(L"twitter", null, reqId);
	if(IsFailed(r))
	{
		AppLog("Fail to GetProfile. [%s]", GetErrorMessage(r));
	}

}
void MySnsGatewayManager::RequestProfileFollowingByIndex(int index) {
	SnsProfile*pSnsProfile =
			static_cast<SnsProfile*> (__pBuddyMemberList->GetAt(index));
	RequestId reqId;
	result r;
	__isMyProfile = false;
	String userId = pSnsProfile->GetSnsUserId();
	r = __pSnsGateway->GetProfile(L"twitter", &userId, reqId);
	if(IsFailed(r))
	{
		AppLog("Fail to GetProfile. [%s]", GetErrorMessage(r));
	}
}
void MySnsGatewayManager::RequestFollowingList() {
	SnsPagingParam pagingParam(10);
	RequestId reqId;
	result r = E_SUCCESS;
	r = __pSnsGateway->GetMyBuddies(L"twitter", pagingParam, reqId);
	if(IsFailed(r))
	{
		AppLog("Fail to GetMyBuddies. [%s]", GetErrorMessage(r));
	}
}
void MySnsGatewayManager::RequestPhotoByUser() {
	int index = 1;
	SnsPagingParam pagingParam(10);
	SnsProfile*pSnsProfile =
			static_cast<SnsProfile*> (__pBuddyMemberList->GetAt(index));
	RequestId reqId;
	result r;
	__isMyProfile = false;
	String userId = pSnsProfile->GetSnsUserId();
	r = __pSnsGateway->GetProfile(L"twitter", &userId, reqId);
	if(IsFailed(r))
	{
		AppLog("Fail to GetProfile. [%s]", GetErrorMessage(r));
	}

	r=__pSnsGateway->GetPhotosByUser(L"twitter",&userId,pagingParam,reqId);
}
void MySnsGatewayManager::OnSnsLoggedInStatusReceived(RequestId reqId,
		Osp::Base::String& serviceProvider, bool isLoggedIn, result r,
		const Osp::Base::String& errorCode, const Osp::Base::String& errorMsg) {
	AppLog("Thanh cong OnSnsLoggedInStatusReceived");
	Frame* pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
	Form1* pMgr = static_cast<Form1*> (pFrame->GetControl(L"Twitter_LoginForm"));

	if (IsFailed(r))
	{
		AppLog("OnSnsLoggedInStatusReceived() is failed. [%s][%S][%S]",GetErrorMessage(r), errorCode.GetPointer(), errorMsg.GetPointer());
		}

		pMgr->SetLoginStatus(isLoggedIn);
}
void MySnsGatewayManager::UpdateMyStatusText(String myStatusText) {
	RequestId reqId;
	result r = E_SUCCESS;
	r = __pSnsGateway->UpdateMyStatusText("twitter", myStatusText, reqId);
	if (IsFailed(r) || reqId == INVALID_REQUEST_ID) {
		return;
	}
}
SnsProfile* MySnsGatewayManager::GetSnsProfileByIndex(int index) {
	AppLog("BuddyMemBerList:%d",__pBuddyMemberList->GetCount());
	SnsProfile*pMySnsProfile =
			static_cast<SnsProfile*> (__pBuddyMemberList->GetAt(index));
	return pMySnsProfile;
}
// Activity Listener
void MySnsGatewayManager::OnSnsActivitiesReceivedN(RequestId reqId,
		Osp::Base::Collection::IList* pActivityList, bool hasNext,
		Osp::Social::Services::SnsPagingParam& pagingParam, result r,
		const Osp::Base::String& errorCode, const Osp::Base::String& errorMsg) {
	AppLog("OnSnsActivitiesReceivedN");
	Frame* pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
	//Form1* pMgr = static_cast<Form1*> (pFrame->GetControl(L"IDF_FORM1"));
	TwitterForm* pMgr = static_cast<TwitterForm*> (pFrame->GetControl(L"Twitter_FormMain"));

	if (IsFailed(r))
	{
		//	Util::ShowMessage(L"Error!", L"Sorry, can't get the activities.");
			AppLog("OnSnsActivitiesReceivedN() is failed. [%s][%S][%S]",GetErrorMessage(r), errorCode.GetPointer(), errorMsg.GetPointer());
			pMgr->ThongBaoLoi("Việc lấy dữ liệu từ server thất bại");
	}

		if (__pPagingParam)
		{
			delete __pPagingParam;
			__pPagingParam = null;
		}

		if (hasNext == true)
		{
			__pPagingParam = new SnsPagingParam(pagingParam);
		}

		pMgr->AddActivities(pActivityList);
		if( pActivityList != null )
		{
			pActivityList->RemoveAll(true);
			delete pActivityList;
			pActivityList = null;
		}
}

	// People Listener
void MySnsGatewayManager::OnMySnsBuddiesReceivedN(RequestId reqId,
		Osp::Base::Collection::IList *pBuddyProfileList, bool hasNext,
		Osp::Social::Services::SnsPagingParam& pagingParam, result r,
		const Osp::Base::String &errorCode, const Osp::Base::String &errorMsg) {
	AppLog("OnMySnsBuddiesReceivedN");
	Frame* pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
	//Form1* pMgr = static_cast<Form1*> (pFrame->GetControl(L"IDF_FORM1"));
	MyFollowingForm* pMgr = static_cast<MyFollowingForm*> (pFrame->GetControl(L"Twitter_FollowingListForm"));
	if (IsFailed(r))
	{
		//	Util::ShowMessage(L"Error!", L"Sorry, can't get the activities.");
		AppLog("OnSnsActivitiesReceivedN() is failed. [%s][%S][%S]",GetErrorMessage(r), errorCode.GetPointer(), errorMsg.GetPointer());
		pMgr->ThongBaoLoi("Việc lấy dữ liệu thất bại");
		return;
	}

	if (__pPagingParamBuddies)
	{
		delete __pPagingParamBuddies;
		__pPagingParamBuddies = null;
	}

	if (hasNext == true)
	{
		__pPagingParamBuddies = new SnsPagingParam(pagingParam);
	}

	if (__pBuddyMemberList != null) {
		__pBuddyMemberList->RemoveAll(true);
		delete __pBuddyMemberList;
		__pBuddyMemberList = null;
	}
	__pBuddyMemberList = pBuddyProfileList;
	AppLog("BuddyProfileList:%d", pBuddyProfileList->GetCount());
	AppLog("BuddyMemBerList:%d",__pBuddyMemberList->GetCount());
	pMgr->AddFollowingList(pBuddyProfileList);
	/*

	 pMgr->AddFollowingList(pBuddyProfileList);
	 if( pBuddyProfileList != null )
	 {
	 pBuddyProfileList->RemoveAll(true);
	 delete pBuddyProfileList;
	 pBuddyProfileList = null;
	 }
	 */

}
void MySnsGatewayManager::OnMySnsStatusTextUpdated(RequestId reqId,
		Osp::Base::String &serviceProvider, result r,
		const Osp::Base::String &errorCode, const Osp::Base::String &errorMsg) {
	Frame* pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
	//Form1* pMgr = static_cast<Form1*> (pFrame->GetControl(L"IDF_FORM1"));
	TwitterForm* pMgr = static_cast<TwitterForm*> (pFrame->GetControl(L"Twitter_FormMain"));

	if(IsFailed(r))
	{
		AppLog("Fail to MySnsStatus Text Updated");
		return;
	}
	pMgr->DisplayResultUpdateStatusText();

}
void MySnsGatewayManager::OnSnsStatusTextReceived(RequestId reqId,
		Osp::Social::Services::SnsStatusText* pStatusText, result r,
		const Osp::Base::String& errorCode, const Osp::Base::String& errorMsg) {
	AppLog("OnSnsStatusTextReceived");
}
void MySnsGatewayManager::OnSnsProfileReceived(RequestId reqId,
		Osp::Social::Services::SnsProfile *pProfile, result r,
		const Osp::Base::String &errorCode, const Osp::Base::String &errorMsg) {
	AppLog("OnSnsProfileReceived");
	Frame* pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
	TwitterForm* pTwitterForm = static_cast<TwitterForm*> (pFrame->GetControl(L"Twitter_FormMain"));
					MyProfileForm* pMgr = static_cast<MyProfileForm*> (pFrame->GetControl(L"Twitter_MyProfileForm"));
					TwitterUsernameProfileForm* pUserNameProfileForm = static_cast<TwitterUsernameProfileForm*> (pFrame->GetControl(L"TwitterUserNameProfileForm"));
					if (IsFailed(r))
					{
						AppLog("OnSnsProfileReceived() is failed. [%s][%S][%S]",GetErrorMessage(r), errorCode.GetPointer(), errorMsg.GetPointer());
						if (__isMyProfile == true)
						{
							pMgr->ThongBaoLoi("Việc lấy dự liệu thông tin cá nhân thất bại");
						}
						else
						{
							pUserNameProfileForm->ThongBaoLoi("Việc lấy dữ liệu thông tin cá nhân thất bại");
						}
						return;
					}
					if(__isGetMyUserNameProfile==true)
					{
						String userName;
						pProfile->GetValue(SNS_PROFILE_PID_DISPLAY_NAME, userName);
						pTwitterForm->SetMyUseName(userName);
						__isGetMyUserNameProfile=false;
					} else
					{
						IList* pListData = null;
						IEnumerator* pEnum = null;
						String displayName, userName, location, url, statusText, profileText;
						Address* pAddress = null;
						String* pUrl = null;
						SnsStatusText status;
						DateTime updateTime;

						//make string to display
						pProfile->GetValue(SNS_PROFILE_PID_USER_NAME, userName);
						pProfile->GetValue(SNS_PROFILE_PID_DISPLAY_NAME, displayName);
						status = pProfile->GetStatusText();
						statusText = status.GetStatusText();
						updateTime = status.GetUpdateTime();
						pListData = pProfile->GetValueN(SNS_PROFILE_PID_ADDRESSES);
						pEnum = pListData->GetEnumeratorN();
						while (pEnum->MoveNext() != E_OUT_OF_RANGE)
						{
							pAddress = static_cast<Address*>(pEnum->GetCurrent());
							location = pAddress->GetCity();
						}
						delete pEnum;
						pEnum = null;
						pListData->RemoveAll(true);
						delete pListData;
						pListData = null;

						pListData = pProfile->GetValueN(SNS_PROFILE_PID_URLS);
						pEnum = pListData->GetEnumeratorN();
						while (pEnum->MoveNext() != E_OUT_OF_RANGE)
						{
							pUrl = static_cast<String*>(pEnum->GetCurrent());
							url = *pUrl;
						}
						delete pEnum;
						pEnum = null;
						pListData->RemoveAll(true);
						delete pListData;
						pListData = null;

						profileText.Append(L"\nName: ");
						profileText.Append(userName);
						profileText.Append(L"\nDisplay Name: ");
						profileText.Append(displayName);
						profileText.Append(L"\nLocation: ");
						profileText.Append(location);
						profileText.Append(L"\nURLs: ");
						profileText.Append(url);
						profileText.Append(L"\nRecent status: ");
						profileText.Append(statusText);
						profileText.Append(L"\n");
						profileText.Append(updateTime.ToString());

						if (__isMyProfile == true)
						{
							pMgr->SetMyProfileToEditArea(profileText, location);
						}
						else
						{
							pUserNameProfileForm->SetUserNameProfileToEditArea(profileText, location );
						}
					}
				}
